package ca.etsmtl.gti785.util;

import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletResponse;
import ca.etsmtl.gti785.Server;

/**
 * This is the server observer to keep the http requests rolling. 
 * When the observer gets a notification from the server, he releases the requests, causing a notification for the client side.
 * @author Étienne Faucher
 */
public class ServerObserver implements Observer, Runnable 
{
	private final BlockingQueue<AsyncContext> _suspended = new ArrayBlockingQueue<AsyncContext>(50);
	private Thread _thread;
	
	private static ServerObserver _instance; 
	
	public static ServerObserver getInstanceOf()
	{
		if(_instance == null)
		{
			_instance = new ServerObserver();
		}
		
		return _instance;
	}
	
	private ServerObserver()
	{
		Server.getInstanceOf().addObserver(this);
		
		_thread = new Thread(this);
		_thread.start();
	}
	
	public void AddAsyncContext(AsyncContext context)
	{
		_suspended.add(context);
	}
	
	public boolean DeleteAsyncContext(AsyncContext context)
	{
		return _suspended.remove(context);
	}

	@Override
	public void update(Observable arg0, Object arg1) 
	{
		for(AsyncContext context : _suspended)
		{
			HttpServletResponse response = (HttpServletResponse) context.getResponse();
			if(response != null)
			{
				response.setStatus(HttpServletResponse.SC_OK);
			}
			
			context.complete();
		}
		
		_suspended.clear();
	}

	@Override
	public void run() 
	{		
		while(true)
		{
		}
	}

}
